<script lang="tsx" setup>
import { type DataTableColumns, NCard, NDataTable, NButton, NTag, NDivider, NSpace } from "naive-ui";
import { ref, shallowRef } from "vue";
import { useI18n } from "@/hooks/useI18n";
import { getPermissions } from "@/api/user";
import type { Permission } from "@/typings/permission";
import { RenderIcon5ByName } from "@/components/icon/RenderIcon";
import MenuAction from "./components/menuAction.vue";

// 表格数据
const menuList = shallowRef<Permission[]>([]);

const isLoading = ref(false);

const rowKey = (row: Permission) => row.id;

// 查询菜单
const getMenus = async () => {
  try {
    isLoading.value = true;
    const { success, data } = await getPermissions();
    isLoading.value = false;
    if (!success) return;
    menuList.value = data;
  } catch (error) {}
};

getMenus();

const { t } = useI18n();

// 表头数据
const columns: DataTableColumns<Permission> = [
  { title: "菜单名称", key: "name", render: ({ name }) => t(name), minWidth: 120 },
  { title: "图标", key: "icon", render: ({ icon }) => RenderIcon5ByName(icon)(), minWidth: 80 },
  { title: "重定向", key: "redirect", minWidth: 200 },
  { title: "路由", key: "path", minWidth: 200 },
  { title: "组件路径", key: "component", minWidth: 200 },
  {
    title: "是否启用",
    key: "enable",
    minWidth: 120,
    render: ({ enable }) => {
      return <NTag type={enable ? "success" : "warning"}>{enable ? "是" : "否"}</NTag>;
    },
  },
  {
    title: "是否展示",
    key: "show",
    minWidth: 120,
    render: ({ enable }) => {
      return <NTag type={enable ? "success" : "warning"}>{enable ? "是" : "否"}</NTag>;
    },
  },
  {
    title: "操作",
    key: "action",
    render: () => {
      return (
        <div class={`flex justify-around`}>
          <NButton secondary size="tiny">
            新增
          </NButton>
          <NButton secondary size="tiny">
            修改
          </NButton>
          <NButton secondary size="tiny">
            删除
          </NButton>
        </div>
      );
    },
  },
];

// menuActionRef
const menuActionRef = ref<InstanceType<typeof MenuAction> | null>(null);

const addMenu = () => {
  menuActionRef.value?.controlVisible();
};
</script>

<template>
  <div>
    <NCard>
      <NSpace justify="end">
        <NButton type="primary" @click="addMenu"> 新建 </NButton>
      </NSpace>
      <NDivider />
      <NDataTable :columns="columns" :data="menuList" :loading="isLoading" :row-key="rowKey" />
    </NCard>
    <MenuAction ref="menuActionRef" />
  </div>
</template>

<style lang="less" scoped></style>
